<template>
  <div style="width:90%;">
    <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
      <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>
      <el-input v-model="planForm.uuid" type="hidden"></el-input>
      <el-input v-model="planForm.orgSeq" type="hidden"></el-input>
      <el-form-item label="方案名称：" prop="planName">
        <el-input
          v-model="planForm.planName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入方案名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>
      <!--
      <el-form-item label="方案图片：" prop="planPicture">
        <el-upload name="planForm.planPicture" class="upload-demo" 
          action="http://mt.wssaa.com/api/file-service/v1/file/uploadFile"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :on-success="upLoadPic"
          list-type="picture" :limit="1" style="width:80%">
          <el-button type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      -->
      <el-form-item label="方案说明：" prop="planDesc">
        <el-input
          type="textarea"
          v-model="planForm.planDesc"
          :disabled="disabledFlag"
          placeholder="请输入方案说明"
          maxlength="120"
          show-word-limit
          :autosize="{minRows:2}"
          style="width:650px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="促销方式：" prop="promotionType">
        <el-radio-group v-model="planForm.promotionType" :disabled="true">
          <el-radio-button label="1">现金</el-radio-button>
          <el-radio-button label="2">满减</el-radio-button>
          <el-radio-button label="3">满折</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="开始时间：" prop="beginTime">
        <el-date-picker
          v-model="planForm.beginTime"
          type="date"
          placeholder="请选择开始时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width:325px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间：" prop="endTime">
        <el-date-picker
          v-model="planForm.endTime"
          type="date"
          placeholder="请选择结束时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width:325px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-radio-group v-model="planForm.status" :disabled="disabledFlag">
          <el-radio-button label="0">不发布</el-radio-button>
          <el-radio-button label="1">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="投放卡券：" prop="planCouponList">
        <el-table
          :data="planCouponList"
          @selection-change="planCouponChecked"
          border
          style="font-size: 10px;width:100%;"
          height="300"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <!--<el-table-column prop="couponNo" label="卡券编号" width="200" header-align="center"></el-table-column>-->
          <el-table-column prop="couponName" label="卡券名称" width="220" header-align="center"></el-table-column>
          <el-table-column prop="couponType" label="卡券类型" width="100" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.couponType == '1'">现金券</span>
              <span v-if="scope.row.couponType == '2'">满减券</span>
              <span v-if="scope.row.couponType == '3'">满折券</span>
            </template>
          </el-table-column>
          <!--<el-table-column prop="conponLimitMoney" label="使用条件" width="100" header-align="center" align="right"></el-table-column>-->
          <el-table-column
            prop="couponMoney"
            label="卡券面值"
            width="120"
            header-align="center"
            align="left"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.couponType == '3'"
              >满{{scope.row.conponLimitMoney}}打{{scope.row.couponDiscount * 10}}折</span>
              <span
                v-if="scope.row.couponType != '3'"
              >满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
            </template>
          </el-table-column>
          <el-table-column prop="validDate" label="卡券有效期" header-align="center" width="160">
            <template slot-scope="scope">
              <span v-if="scope.row.validType == '1'">领取后{{scope.row.validDate}}天</span>
              <span
                v-if="scope.row.validType == '2'"
              >{{scope.row.validCreateDate}}至{{scope.row.validEndDate}}</span>
              <!--
              <span v-if="scope.row.validType == '2'">
                <el-date-picker v-model="scope.row.beginTime" type="date" placeholder="生效日期" 
                  value-format="yyyy-MM-dd" :disabled="disabledFlag" :clearable="false" style="width:150px;"></el-date-picker>至
                <el-date-picker v-model="scope.row.endTime" type="date" placeholder="失效日期" 
                  value-format="yyyy-MM-dd" :disabled="disabledFlag" :clearable="false" style="width:150px;"></el-date-picker>
              </span>
              -->
            </template>
          </el-table-column>
          <el-table-column
            prop="sumCouponSumQuantity"
            label="投放数量"
            width="100"
            header-align="center"
            align="right"
          ></el-table-column>
          <el-table-column
            prop="sumCouponQuantity"
            label="剩余数量"
            width="100"
            header-align="center"
            align="right"
          ></el-table-column>
          <!--
          <el-table-column prop="useScope" label="商品范围" header-align="center"></el-table-column>
          <el-table-column prop="isStoreLevel" label="门店等级" header-align="center"></el-table-column>
          -->
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="selectShop(scope.row, scope.$index)">选择门店</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectCoupon('planForm')" v-if="!disabledFlag">选择卡券</el-button>
          <el-button @click="deleteCoupon('planForm')" v-if="!disabledFlag">删除卡券</el-button>
        </div>
      </el-form-item>

      <el-form-item label="会员等级：">
        <el-radio-group v-model="planForm.memberRange" :disabled="disabledFlag">
          <el-radio-button label="1">通用</el-radio-button>
          <el-radio-button label="2">指定会员等级</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="适用会员等级：" prop="planMemberRangeList" v-if="planForm.memberRange == '2'">
        <el-table
          :data="planMemberRangeList"
          @selection-change="planMemberLevelChecked"
          border
          v-if="planForm.memberRange == '2'"
          style="font-size: 10px;width:80%;"
          height="300"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="gradelevelName" label="等级名称" width="180" header-align="center"></el-table-column>
          <el-table-column
            prop="levelNumber"
            label="等级序号"
            width="180"
            header-align="center"
            align="center"
          ></el-table-column>
          <el-table-column prop="beginScore" label="积分范围" header-align="center" align="right">
            <template slot-scope="scope">{{scope.row.beginScore}}至{{scope.row.endScore}}</template>
          </el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button
            type="primary"
            @click="selectMemberRange('planForm')"
            v-if="!disabledFlag"
          >选择会员等级</el-button>
          <el-button @click="deleteMemberRange('planForm')" v-if="!disabledFlag">删除会员等级</el-button>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('planForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('planForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择卡券" :visible.sync="dialogVisibleCoupon" width="55%">
      <el-form
        :inline="true"
        :model="formCoupon"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        <el-input v-model="formCoupon.couponName" style="width:200px;" placeholder="卡券名称"></el-input>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getCouponList()">查询</el-button>
      </el-form>
      <el-table
        :data="couponList"
        @selection-change="couponChecked"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <!--<el-table-column prop="couponNo" label="卡券编号" width="200" header-align="center"></el-table-column>-->
        <el-table-column prop="couponName" label="卡券名称" width="250" header-align="center"></el-table-column>
        <el-table-column prop="couponType" label="卡券类型" width="120" header-align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.couponType == '1'">现金券</span>
            <span v-if="scope.row.couponType == '2'">满减券</span>
            <span v-if="scope.row.couponType == '3'">满折券</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="conponLimitMoney" label="使用条件" width="100" header-align="center" align="right"></el-table-column>-->
        <el-table-column
          prop="couponMoney"
          label="卡券面值"
          width="120"
          header-align="center"
          align="left"
        >
          <template slot-scope="scope">
            <span
              v-if="scope.row.couponType == '3'"
            >满{{scope.row.conponLimitMoney}}打{{scope.row.couponDiscount * 10}}折</span>
            <span
              v-if="scope.row.couponType != '3'"
            >满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="validDate" label="卡券有效期" header-align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.validType == '1'">领取后{{scope.row.validDate}}天</span>
            <span
              v-if="scope.row.validType == '2'"
            >{{scope.row.validCreateDate}}至{{scope.row.validEndDate}}</span>
          </template>
        </el-table-column>
        <!--
        <el-table-column prop="useScope" label="商品范围" header-align="center"></el-table-column>
        <el-table-column prop="isStoreLevel" label="门店等级" header-align="center"></el-table-column>
        -->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
        <el-button type="primary" @click="couponConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择店铺" :visible.sync="dialogVisibleShop" width="65%">
      <el-form
        :inline="true"
        :model="formShop"
        class="search-form-inline"
        style="margin-top:-20px;"
      >
        <el-input v-model="formShop.shopName" style="width:200px;" placeholder="店铺名称"></el-input>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getShopList()">查询</el-button>
      </el-form>
      <el-table
        ref="shopTable"
        :data="shopList"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        @selection-change="shopChecked"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <!--
        <el-table-column prop="orgSeq" label="店铺编号" width="200" header-align="center"></el-table-column>
        -->
        <el-table-column prop="storeName" label="店铺名称" width="180" header-align="center"></el-table-column>
        <el-table-column prop="storeOwnerName" label="店主姓名" width="100" header-align="center"></el-table-column>
        <el-table-column prop="storeType" label="店铺类型" width="100" header-align="center">
          <template slot-scope="scope">
            <template v-for="item in storeType">
              <span v-if="scope.row.storeType == item.value" :key="item.value">{{ item.label }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="storeAddressDetail" label="店铺地址" header-align="center"></el-table-column>
        <el-table-column prop="couponSumQuantity" label="投放数量" width="120" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.couponSumQuantity"
              :value="scope.row.couponSumQuantity"
              @blur="quantityBlur($event, scope.$index)"
              :disabled="disabledFlag"
              style="width:80px;text-align:right;text-align-last:right;"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="couponQuantity"
          label="剩余数量"
          width="100"
          header-align="center"
          align="right"
        ></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShop = false">取 消</el-button>
        <el-button type="primary" @click="shopConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择会员等级" :visible.sync="dialogVisibleMemberRange" width="50%">
      <el-table
        :data="memberRangeList"
        @selection-change="memberLevelChecked"
        border
        style="font-size: 10px;width:100%;margin-top:-20px;"
        height="300"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="gradelevelName" label="等级名称" width="180" header-align="center"></el-table-column>
        <el-table-column
          prop="levelNumber"
          label="等级序号"
          width="180"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column prop="beginScore" label="积分范围" header-align="center" align="right">
          <template slot-scope="scope">{{scope.row.beginScore}}至{{scope.row.endScore}}</template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleMemberRange = false">取 消</el-button>
        <el-button type="primary" @click="memberRangeConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="查看图片" :visible.sync="dialogVisibleImg" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import {
  queryPromotionList,
  queryPromotionById,
  queryCouponById,
  savePromotion,
  updatePromotionStatus,
  queryStoreByPlanId,
  queryStoreInfo,
  createTPlan
} from "@/api/promotionProgramEdit";

import { queryCouponList } from "@/api/promotionProgramEdit";
import { queryGradelevelRule } from "@/api/membergrade";
import { dict } from '../../dict';

export default {
  data() {
    return {
      logininfo: {},
      orgList: [],
      orgSeq: "",
      loading: true,
      lsPlanCouponList: [],
      lsCouponList: [],
      planCouponList: [],
      couponList: [],
      planMemberRangeList: [],
      memberRangeList: [],
      lsPlanMemberLevelList: [],
      lsMemberLevelList: [],
      lsCouponIndex: "",
      lsShopList: [],
      shopList: [],
      couponUseScopeList: [],
      couponShopLevelList: [],
      currentCouponId: "",
      currentCouponLevelIds: "",
      fileList: [],
      planForm: {
        uuid: "",
        planName: "",
        // planPicture: "",
        planDesc: "",
        promotionType: "",
        beginTime: "",
        endTime: "",
        memberRange: "",
        status: "",
        promotionCouponInfo: [],
        promotionPlanMemberlevel: []
      },
      formCoupon: {
        couponName: ""
      },
      formShop: {
        shopName: ""
      },
      dialogVisibleCoupon: false,
      dialogVisibleShop: false,
      dialogVisibleMemberRange: false,
      disabledFlag: false,
      dialogVisibleImg: false,
      dialogImageUrl: "",
      listQuery: {
        current: 1,
        size: 10
      },
      total: 0,
      planRules: {
        /*
        planName: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
        beginTime: [{ required: true, message: "请选择开始时间", trigger: "blur" }],
        endTime: [{ required: true, message: "请选择结束时间", trigger: "blur" }]
        */
      }
    };
  },
  computed: {
    storeType: () => dict.storeType
  },
  mounted() {
    this.logininfo = localStorage.getItem("logininfo");
    this.orgList = JSON.parse(this.logininfo).orgList;
    this.orgSeq = this.orgList[0].orgSeq;
    this.planForm.orgSeq = this.orgList[0].orgSeq;

    var v = this.$route.params.edit;
    if (v) {
      // 修改，回显值
      this.planForm.uuid = v.uuid;
      this.planForm.planName = v.planName;
      // this.planForm.planPicture = v.planPicture;
      this.planForm.planDesc = v.planDesc;
      this.planForm.promotionType = v.promotionType;
      this.planForm.beginTime = v.beginTime;
      this.planForm.endTime = v.endTime;
      this.planForm.memberRange = v.memberRange;
      this.planForm.status = v.status;

      this.queryPromotionById(v.uuid);
    } else {
      // 新增，默认值
      this.planForm.uuid = "";
      this.planForm.promotionType = "1";
      this.planForm.memberRange = "1";
      this.planForm.status = "0";
      this.getCouponList();
      this.getMemberlevel();
    }
  },
  methods: {
    goback() {
      this.$router.go("-1");
    },
    quantityBlur(e, idx) {
      if (e.target.value == '') { return; }
      var obj = this.shopList[idx];
      var oldleft = obj.couponQuantityOld;
      var oldsum = obj.couponSumQuantityOld;

      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: "投放数量请输入正整数",
          type: "warning"
        });
        e.target.value = oldsum;
      } else {
        oldsum = parseInt(oldsum == null ? '0' : oldsum);
        oldleft = parseInt(oldleft == null ? '0': oldleft);
        var received = oldsum - oldleft;
        var left = oldleft;
        var val = parseInt(e.target.value);
        if (oldsum == oldleft) {
          // 相等说明未被领取，可以修改投放数量
          left = val;
          obj.couponQuantity = left;
        } else {
          // 不等说明已被领取，不可修改投放数量，计算剩余数量
          if (val >= received) {
            left = val - oldsum + oldleft;
            obj.couponQuantity = left;
          } else {
            this.$message({
              message: "投放数量不能小于已领取数量，请重新输入",
              type: "warning"
            });
            e.target.value = oldsum;
            obj.couponQuantity = oldleft;
          }
        }
        this.$set(this.shopList, idx, obj);
      }
    },
    queryPromotionById(uuid) {
      queryPromotionById(uuid, "").then(res => {
        if (
          res.result != null &&
          res.result.promotionCouponInfo != null &&
          res.result.promotionCouponInfo.length > 0
        ) {
          this.planCouponList = res.result.promotionCouponInfo;
        }
        if (
          res.result != null &&
          res.result.promotionPlanMemberlevel != null &&
          res.result.promotionPlanMemberlevel.length > 0
        ) {
          this.planMemberRangeList = res.result.promotionPlanMemberlevel;
        }
        this.getCouponList();
        this.getMemberlevel();
      });
      this.loading = false;
    },
    getShopList() {
      let data = {
        size: this.listQuery.size,
        current: this.listQuery.current,
        condition: {
          zqOrgSeq: this.orgSeq,
          planId: this.planForm.uuid,
          couponId: this.currentCouponId,
          gradelevelId: this.currentCouponLevelIds,
          storeName: this.formShop.shopName
        },
        ascs: [],
        descs: []
      };
      if (this.planForm.uuid != null && this.planForm.uuid != "") {
        // 修改方案，调用查询卡券门店的接口
        queryStoreByPlanId(data).then(res => {
          this.shopList = res.records;
          this.total = res.total;
          // 设置回显
          this.checkboxInit();
        });
      } else {
        // 新增方案，调用仅查询门店的接口
        queryStoreInfo(data).then(res => {
          this.shopList = res.records;
          this.total = res.total;
          // 设置回显
          this.checkboxInit();
        });
      }
      this.loading = false;
    },

    checkboxInit() {
      var that = this;
      that.$nextTick(function() {
        if (
          that.planCouponList[that.lsCouponIndex].userStoreInfo == null ||
          that.shopList == null
        ) {
          return;
        }
        if (that.$refs.shopTable) {
          that.$refs.shopTable.clearSelection();
        }
        that.planCouponList[that.lsCouponIndex].userStoreInfo.forEach(row => {
          that.shopList.forEach(shop => {
            if (row.orgSeq == shop.orgSeq) {
              that.$refs.shopTable.toggleRowSelection(shop, true);
              shop["planUuid"] = row.planUuid == null ? "" : row.planUuid;
              if (
                row.couponSumQuantity != null &&
                row.couponSumQuantity != ""
              ) {
                shop.couponSumQuantity = row.couponSumQuantity;
                // this.$set(shop, 'couponSumQuantity', row.couponSumQuantity);
              }
              if (row.couponQuantity != null && row.couponQuantity != '') {
                shop.couponQuantity = row.couponQuantity;
              }
            }
          });
        });
      });
    },

    getCouponList() {
      let data = {
        size: 20,
        current: 1,
        condition: {
          status: 1,
          // couponType: this.planForm.promotionType,
          couponName: this.formCoupon.couponName
        },
        ascs: [],
        descs: []
      };
      queryCouponList(data).then(res => {
        this.couponList = res.records;
        // 去掉已选的
        for (var i in this.planCouponList) {
          this.removeByValue(
            this.couponList,
            "uuid",
            this.planCouponList[i].uuid
          );
        }
      });
      this.loading = false;
    },
    getMemberlevel() {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: []
      };
      queryGradelevelRule(data).then(res => {
        this.memberRangeList = res.records;
        // 去掉已选的
        for (var i in this.planMemberRangeList) {
          this.removeByValue(
            this.memberRangeList,
            "uuid",
            this.planMemberRangeList[i].uuid
          );
        }
      });
      this.loading = false;
    },

    planCouponChecked(row) {
      this.lsPlanCouponList = row;
    },
    couponChecked(row) {
      this.lsCouponList = row;
    },
    selectCoupon() {
      // 显示选择卡券对话框
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
    },
    deleteCoupon() {
      // 删除已选择的卡券
      this.couponList = this.couponList.concat(this.lsPlanCouponList);
      for (var i in this.lsPlanCouponList) {
        this.removeByValue(
          this.planCouponList,
          "uuid",
          this.lsPlanCouponList[i].uuid
        );
      }
    },
    couponConfirm() {
      // 保存已选择的卡券
      /*
      for (var i in this.lsCouponList) {
        if ((this.lsCouponList[i].beginTime == null || this.lsCouponList[i].beginTime == '')
          && (this.lsCouponList[i].validCreateDate != null && this.lsCouponList[i].validCreateDate != '')) {
          this.lsCouponList[i].beginTime = this.lsCouponList[i].validCreateDate.substring(0,10);
        }
        if ((this.lsCouponList[i].endTime == null || this.lsCouponList[i].endTime == '') 
          && (this.lsCouponList[i].validEndDate != null && this.lsCouponList[i].validEndDate != '')) {
          this.lsCouponList[i].endTime = this.lsCouponList[i].validEndDate.substring(0,10);
        }
      }
      */
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.planCouponList = this.planCouponList.concat(this.lsCouponList);
      for (var i in this.lsCouponList) {
        this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
      }
    },

    selectShop(row, index) {
      this.lsCouponIndex = index;
      var ids = "";
      // 查询卡券的门店等级
      queryCouponById(row.uuid).then(res => {
        if (res.result == null || res.result.storeGradelevelRuleDTOS == null) {
          this.couponShopLevelList = [];
        } else {
          this.couponShopLevelList = res.result.storeGradelevelRuleDTOS;
        }
        for (var i in this.couponShopLevelList) {
          if (i == 0) {
            ids += this.couponShopLevelList[i].uuid;
          } else {
            ids += "," + this.couponShopLevelList[i].uuid;
          }
        }
        this.currentCouponId = row.uuid;
        this.currentCouponLevelIds = ids;
        // 查询门店列表
        this.getShopList();
      });
      // 显示选择门店对话框
      this.dialogVisibleShop = !this.dialogVisibleShop;
    },
    shopChecked(row) {
      this.lsShopList = row;
    },
    shopConfirm() {
      // 保存已选择的门店
      var flag1 = true;
      var flag2 = true;
      var flag3 = true;
      // 投放数量校验、计算总数
      var sum = 0;
      var leftSum = 0;
      for (var i in this.lsShopList) {
        var quantity = this.lsShopList[i].couponSumQuantity;
        if (quantity == null || quantity == "") {
          flag1 = false;
          break;
        }
        let f = new RegExp("^[1-9][0-9]*$").test(quantity);
        if (!f) {
          flag2 = false;
          break;
        }
        if (parseInt(quantity) < parseInt(this.lsShopList[i].couponQuantity)) {
          flag3 = false;
          break;
        }
        sum += parseInt(quantity);
        var leftQuantity = this.lsShopList[i].couponQuantity;
        leftQuantity = parseInt((leftQuantity == null || leftQuantity == undefined) ? '0' : leftQuantity);
        leftSum += leftQuantity;
      }
      if (!flag1) {
        this.$message({
          message: "请输入已选门店的投放数量",
          type: "warning"
        });
        return;
      }
      if (!flag2) {
        this.$message({
          message: "投放数量请输入正整数",
          type: "warning"
        });
        return;
      }
      if (!flag3) {
        this.$message({
          message: "投放数量不能小于已领取数量，请重新输入",
          type: "warning"
        });
        return;
      }
      this.dialogVisibleShop = false;
      var obj = this.planCouponList[this.lsCouponIndex];
      obj['userStoreInfo'] = this.lsShopList;
      obj['sumCouponSumQuantity'] = sum;
      obj['sumCouponQuantity'] = leftSum;
      this.$set(this.planCouponList, this.lsCouponIndex, obj);
    },

    planMemberLevelChecked(row) {
      this.lsPlanMemberLevelList = row;
    },
    memberLevelChecked(row) {
      this.lsMemberLevelList = row;
    },
    selectMemberRange() {
      // 显示选择会员等级对话框
      this.dialogVisibleMemberRange = !this.dialogVisibleMemberRange;
    },
    deleteMemberRange() {
      // 删除已选择的会员等级
      this.memberRangeList = this.memberRangeList.concat(
        this.lsPlanMemberLevelList
      );
      for (var i in this.lsPlanMemberLevelList) {
        this.removeByValue(
          this.planMemberRangeList,
          "uuid",
          this.lsPlanMemberLevelList[i].uuid
        );
      }
    },
    memberRangeConfirm() {
      // 保存已选择的会员等级
      this.dialogVisibleMemberRange = !this.dialogVisibleMemberRange;
      this.planMemberRangeList = this.planMemberRangeList.concat(
        this.lsMemberLevelList
      );
      for (var i in this.lsMemberLevelList) {
        this.removeByValue(
          this.memberRangeList,
          "uuid",
          this.lsMemberLevelList[i].uuid
        );
      }
    },

    submitForm(formName) {
      // 保存方案
      if (this.planForm.planName == "" || this.planForm.planName == null) {
        this.$message.error("请输入方案名称");
        return;
      }
      if (this.planForm.beginTime == "" || this.planForm.beginTime == null) {
        this.$message.error("请输入开始时间");
        return;
      }
      if (this.planForm.endTime == "" || this.planForm.endTime == null) {
        this.$message.error("请输入结束时间");
        return;
      }
      if (this.planForm.beginTime > this.planForm.endTime) {
        this.$message.error("结束时间不能早于开始时间");
        return;
      }
      if (this.planCouponList.length == 0) {
        this.$message.error("请选择卡券");
        return;
      }
      if (
        this.planForm.memberRange == "2" &&
        (this.planMemberRangeList == null ||
          this.planMemberRangeList.length == 0)
      ) {
        this.$message.error("请选择会员等级");
        return;
      }
      for (var i in this.planCouponList) {
        // 删除提交时不需要的属性或容易导致错误的属性
        // this.planCouponList[i].storeLevelId = this.planCouponList[i].uuid;
        if (
          this.planCouponList[i].couponId == null ||
          this.planCouponList[i].couponId == undefined
        ) {
          this.planCouponList[i].couponId = this.planCouponList[i].uuid;
        }
        delete this.planCouponList[i].createTime;
        delete this.planCouponList[i].createUser;
        delete this.planCouponList[i].updateTime;
        delete this.planCouponList[i].updateUser;
        delete this.planCouponList[i].beginTime;
        delete this.planCouponList[i].endTime;
        delete this.planCouponList[i].comments;
        delete this.planCouponList[i].validCreateDate;
        delete this.planCouponList[i].validEndDate;
        for (var j in this.planCouponList[i].userStoreInfo) {
          delete this.planCouponList[i].userStoreInfo[j].agreement;
          delete this.planCouponList[i].userStoreInfo[j].authCode;
          delete this.planCouponList[i].userStoreInfo[j].baseCode;
          delete this.planCouponList[i].userStoreInfo[j].basePersonCode;
          delete this.planCouponList[i].userStoreInfo[j].buildingArea;
          delete this.planCouponList[i].userStoreInfo[j].businessDistrictType;
          delete this.planCouponList[i].userStoreInfo[j].businessLicense;
          delete this.planCouponList[i].userStoreInfo[j].city;
          delete this.planCouponList[i].userStoreInfo[j].companyName;
          delete this.planCouponList[i].userStoreInfo[j].createTime;
          delete this.planCouponList[i].userStoreInfo[j].createUser;
          delete this.planCouponList[i].userStoreInfo[j].distance;
          delete this.planCouponList[i].userStoreInfo[j].distanceStr;
          delete this.planCouponList[i].userStoreInfo[j].distanceUnit;
          delete this.planCouponList[i].userStoreInfo[j].doorwayPic;
          delete this.planCouponList[i].userStoreInfo[j].gradelevelId;
          delete this.planCouponList[i].userStoreInfo[j].leaseholdArea;
          delete this.planCouponList[i].userStoreInfo[j].legalPerson;
          delete this.planCouponList[i].userStoreInfo[j].legalPersonPhone;
          delete this.planCouponList[i].userStoreInfo[j].managerArea;
          delete this.planCouponList[i].userStoreInfo[j].openBeginTime;
          delete this.planCouponList[i].userStoreInfo[j].openDate;
          delete this.planCouponList[i].userStoreInfo[j].openEndTime;
          delete this.planCouponList[i].userStoreInfo[j].openStatus;
          delete this.planCouponList[i].userStoreInfo[j].openTime;
          delete this.planCouponList[i].userStoreInfo[j].openEnTime;
          delete this.planCouponList[i].userStoreInfo[j].practicalArea;
          delete this.planCouponList[i].userStoreInfo[j].province;
          delete this.planCouponList[i].userStoreInfo[j].status;
          delete this.planCouponList[i].userStoreInfo[j].storeAddress;
          delete this.planCouponList[i].userStoreInfo[j].storeAddressDetail;
          delete this.planCouponList[i].userStoreInfo[j].storeLat;
          delete this.planCouponList[i].userStoreInfo[j].storeLng;
          delete this.planCouponList[i].userStoreInfo[j].storeManagerName;
          delete this.planCouponList[i].userStoreInfo[j].storeManagerPhone;
          delete this.planCouponList[i].userStoreInfo[j].storeManagerPic;
          delete this.planCouponList[i].userStoreInfo[j].storeManagerTel;
          delete this.planCouponList[i].userStoreInfo[j].storeOwnerGrade;
          delete this.planCouponList[i].userStoreInfo[j].storeOwnerName;
          delete this.planCouponList[i].userStoreInfo[j].storeOwnerPhone;
          delete this.planCouponList[i].userStoreInfo[j].storeOwnerPic;
          delete this.planCouponList[i].userStoreInfo[j].upOrgSeq;
          delete this.planCouponList[i].userStoreInfo[j].upOrgZone;
          delete this.planCouponList[i].userStoreInfo[j].updateTime;
          delete this.planCouponList[i].userStoreInfo[j].updateUser;
          delete this.planCouponList[i].userStoreInfo[j].warehouseArea;
          delete this.planCouponList[i].userStoreInfo[j].wechatId;
        }
      }
      for (var i in this.planMemberRangeList) {
        if (
          this.planMemberRangeList[i].levelId == null ||
          this.planMemberRangeList[i].levelId == undefined
        ) {
          this.planMemberRangeList[i].levelId = this.planMemberRangeList[
            i
          ].uuid;
          delete this.planMemberRangeList[i].createTime;
          delete this.planMemberRangeList[i].updateTime;
        }
      }
      this.planForm.beginTime = this.planForm.beginTime.substring(0, 10);
      this.planForm.endTime = this.planForm.endTime.substring(0, 10);
      this.planForm.promotionCouponInfo = this.planCouponList;
      this.planForm.promotionPlanMemberlevel = this.planMemberRangeList;
      // console.log(this.planForm);
      createTPlan(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: "保存成功",
            type: "success"
          });
          this.$router.push("promotionList");
        } else {
          this.$message({
            showClose: true,
            message: "保存失败",
            type: "success"
          });
        }
      });
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getShopList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getShopList();
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url
        };
        newfileList.push(data);
      });
      this.fileList = newfileList;
    },
    upLoadPic(file, fileList) {
      var picUrl = file.result;
      var name = fileList.name;
      let data = {
        name: name,
        url: picUrl
      };
      this.fileList.push(data);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("promotionList");
    }
  }
};
</script>
<style lang="less" scoped>
.el-col-20 {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  width: 60%;
}
.el-input {
  width: 60%;
}
.search-form-inline {
  border: 1px solid #ebeef5;
  line-height: 30px;
  padding: 12px;
  margin-bottom: 5px;
}
</style>